package com.wlbx.agent.ui.activity;

import static android.widget.PopupWindow.INPUT_METHOD_NEEDED;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fastlib.utils.permission.FastPermission;
import com.fastlib.utils.permission.OnPermissionCallback;
import com.fastlib.utils.permission.Permission;
import com.orhanobut.logger.Logger;
import com.wlbx.agent.R;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.bean.BillboardListBean;
import com.wlbx.agent.bean.VersionBean;
import com.wlbx.agent.event.UpdateProductListEvent;
import com.wlbx.agent.global.AccountManager;
import com.wlbx.agent.global.Constant;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitCallBack;
import com.wlbx.agent.net.RetrofitRequestInterface;
import com.wlbx.agent.util.AppUtil;
import com.wlbx.agent.util.Constants;
import com.wlbx.agent.util.IntentUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.VersionUtil;
import com.wlbx.agent.view.dialog.CustomDialogSureCancel;
import com.wlbx.agent.view.dialog.QueryDialog;
import com.wlbx.agent.view.rectangleboxedittext.VerificationCodeView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 设置页
 */
public class SettingActivity extends BaseActivity {
    private static final String TAG = "SettingActivity";

    @BindView(R.id.btn_switch_account)
    Button btnSwitchAccount;

    @BindView(R.id.btn_quit_login)
    Button btnQuitLogin;

    @BindView(R.id.rl_account_write_off)
    RelativeLayout rlAccountWriteOff;

    @BindView(R.id.rl_check_new_version)
    RelativeLayout rlCheckNewVersion;

    @BindView(R.id.rl_single_device_login)
    RelativeLayout rlSingleDeviceLogin;

    @BindView(R.id.rl_finger_psw)
    RelativeLayout rlFingerPsw;

    @BindView(R.id.rl_account_psw)
    RelativeLayout rlAccountPsw;

    @BindView(R.id.rl_mobile)
    RelativeLayout rlMobile;

    @BindView(R.id.rl_device_manage)
    RelativeLayout rlDeviceManage;

    @BindView(R.id.tv_layout_top_back_title)
    TextView mTitleTV;
    @BindView(R.id.iv_layout_top_back)
    ImageView mBackIV;

    @BindView(R.id.tv_phone)
    TextView mPhoneTV;

    @BindView(R.id.tv_version_desc)
    TextView tvVersionDesc;

    TextView tvTime,tvPhoneChange,tvGetValidCode;

    private PopupWindow mPopupWindow,mPopupValidCodeWindow;
    //是否通过发送获取验证码
    private boolean sendValidCode=false;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_setting;
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void initData() {
        mTitleTV.setText("设置");
        if(!"".equals((String)SPUtil.get("phone",""))){
            String phone = (String)SPUtil.get("phone","");
            if(phone.length()==11){
                phone = phone.substring(0,3)+"****"+phone.substring(7);
            }
            mPhoneTV.setText(phone);
        }
        tvVersionDesc.setText("版本号："+AppUtil.getAppVersionName(SettingActivity.this));
    }

    @OnClick({R.id.btn_quit_login, R.id.btn_switch_account,R.id.rl_account_write_off,R.id.rl_check_new_version,R.id.rl_single_device_login,R.id.rl_finger_psw,R.id.rl_account_psw,R.id.rl_mobile,R.id.rl_device_manage,R.id.iv_layout_top_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_quit_login:
                showLogout();
                break;
            case R.id.btn_switch_account:
                Toast.makeText(SettingActivity.this, "切换账户", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rl_account_write_off:
                logOff();
                break;
            case R.id.rl_check_new_version:
//                Toast.makeText(SettingActivity.this, "检测新版本", Toast.LENGTH_SHORT).show();
                FastPermission.with(this)
                        .permissions(Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                                     @Override
                                     public void onPermissionSuccess() {
                                         getVersionInfo();
                                     }

                                     @Override
                                     public void onPermissionFailure(String hint) {

                                     }
                                 });

                break;
            case R.id.rl_single_device_login:
                Toast.makeText(SettingActivity.this, "设备管理", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rl_finger_psw:
                startActivity(new Intent(this,FinglePrintActivity.class));
                break;
            case R.id.rl_account_psw:
                startActivity(new Intent(this,ChangePwActivity.class));
                break;
            case R.id.rl_mobile:
                showPopupWindow();
                break;
            case R.id.rl_device_manage:
                Toast.makeText(SettingActivity.this, "设备管理", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_layout_top_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void getVersionInfo() {
        String versionNo= String.valueOf(AppUtil.getAppVersionCode(SettingActivity.this));
        Logger.i("versionNo---"+versionNo);
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .getVersionInfo("01",versionNo)
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i( response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg  = jsonObject.getString("msg");
                        if("1000".equals(rCode)) {
                            VersionBean versionBean=JSON.parseObject(response,VersionBean.class);
                            String forceUpdate=versionBean.getData().getIsMandatory();
                            String downUrl=versionBean.getData().getDownloadUrl();
                            try {

                                if (VersionUtil.compareVersion(versionBean.getData().getVersionNo(), AppUtil.getAppVersionName(SettingActivity.this)) > 0) {
                                    QueryDialog mQueryDialog = new QueryDialog(SettingActivity.this,versionBean.getData().getVersionNo(),"",forceUpdate, new QueryDialog.DialogGoback() {
                                        @Override
                                        public void query() {
                                            updateApk(downUrl, forceUpdate);
                                        }
                                    });
                                    mQueryDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                                    //Y.强制更新；N.非强制更新
                                    if ("Y".equals(forceUpdate)) {
                                        mQueryDialog.setCanceledOnTouchOutside(false);
                                        mQueryDialog.setCancelable(false);
                                        mQueryDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                                            @Override
                                            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                                                return false;
                                            }
                                        });
                                    }
                                    mQueryDialog.show();

                                }else {
                                    Toast.makeText(SettingActivity.this, "当前已经是最新版本", Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else{
                            Toast.makeText(SettingActivity.this,rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }

    private void showLogout() {
        //提示弹窗
        final CustomDialogSureCancel customDialogSureCancel = new CustomDialogSureCancel(mContext);
        customDialogSureCancel.getTitleView().setVisibility(View.GONE);
        customDialogSureCancel.getContentView().setText("确定退出吗？");
        customDialogSureCancel.getSureView().setText("确定");
        customDialogSureCancel.getCancelView().setText("取消");
        customDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Constant.PRODUCT_NAME="";
                Constant.PRODUCT_SUB_TYPE="";
                Constant.PARTNER_ID="";
                Constant.IS_ONLINE="";
                UpdateProductListEvent updateProductListEvent=new UpdateProductListEvent();
                updateProductListEvent.setProductName(Constant.PRODUCT_NAME);
                updateProductListEvent.setProductSubType(Constant.PRODUCT_SUB_TYPE);
                updateProductListEvent.setPartnerId(Constant.PARTNER_ID);
                updateProductListEvent.setIsOnline(Constant.IS_ONLINE);
                EventBus.getDefault().postSticky(updateProductListEvent);
                customDialogSureCancel.cancel();
                AccountManager.setUserLogin(false);
                AccountManager.removeSP();
                Intent intent = new Intent(mActivity,MainActivity.class);
                intent.putExtra("to","0");
                startActivity(intent);
            }
        });
        customDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialogSureCancel.cancel();
            }
        });
        customDialogSureCancel.show();
    }


    /**
     * 注销
     */
    private void logOff() {
        String phone = (String)SPUtil.get("phone","");
        //提示弹窗
        final CustomDialogSureCancel customDialogSureCancel = new CustomDialogSureCancel(mContext);
        customDialogSureCancel.getTitleView().setVisibility(View.VISIBLE);
        customDialogSureCancel.setTitle("提示");
        customDialogSureCancel.getContentView().setText("是否要注销账户："+phone);
        customDialogSureCancel.getContentView().setTextSize(14);
        customDialogSureCancel.getSureView().setText("确定");
        customDialogSureCancel.getCancelView().setText("取消");
        customDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialogSureCancel.cancel();
                logOffAgain();

            }
        });
        customDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialogSureCancel.cancel();
            }
        });
        customDialogSureCancel.show();
    }


    private void logOffAgain() {
        //提示弹窗
        final CustomDialogSureCancel customDialogSureCancel = new CustomDialogSureCancel(mContext);
        customDialogSureCancel.getTitleView().setVisibility(View.VISIBLE);
        customDialogSureCancel.setTitle("提示");
        customDialogSureCancel.getContentView().setText("注销后我们将删除您的所有个人账户信息，并且无法恢复。但是出于监管要求，您名下的保单相关数据我们将继续保存。如果确认要注销，请点击确认。");
        customDialogSureCancel.getContentView().setTextSize(14);
        customDialogSureCancel.getSureView().setText("确定");
        customDialogSureCancel.getCancelView().setText("取消");
        customDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialogSureCancel.cancel();
                logOffApi();

            }
        });
        customDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialogSureCancel.cancel();
            }
        });
        customDialogSureCancel.show();
    }


    public void logOffApi() {
        final Map<String, String> map = new HashMap<>();
        Logger.i(JSON.toJSONString(map));
        RequestManager
                .mRetrofitManager
                .createRequest(RetrofitRequestInterface.class)
                .logout(JSON.toJSONString(map))
                .enqueue(new RetrofitCallBack() {
                    @Override
                    public void onSuccess(String response) {
                        Logger.i( response);
                        JSONObject jsonObject = JSON.parseObject(response);
                        String rCode = jsonObject.getString("code");
                        String rMsg  = jsonObject.getString("msg");
                        if("1000".equals(rCode)) {
                            Toast.makeText(SettingActivity.this, "您的账户已注销成功", Toast.LENGTH_SHORT).show();
                            AccountManager.setUserLogin(false);
                            AccountManager.removeSP();
                            Intent intent = new Intent(mActivity,MainActivity.class);
                            intent.putExtra("to","0");
                            startActivity(intent);
                        }else{
                            Toast.makeText(SettingActivity.this,rMsg,Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Logger.i( t.getMessage());

                    }
                });
    }


    private void showPopupWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_phone_change, null);
            TextView bindphoneTV = view.findViewById(R.id.tv_pop_phone_bind);
            TextView changephoneTV = view.findViewById(R.id.tv_pop_phone_change);
            bindphoneTV.setText("您当前绑定的手机号:"+mPhoneTV.getText());
            changephoneTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPopupWindow.dismiss();
                    if (mPopupValidCodeWindow == null || !mPopupValidCodeWindow.isShowing()) {
                        showPopupValidCodeWindow();
                    }
                }
            });
            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mPopupWindow.setFocusable(false);
                    mPopupWindow.dismiss();
                    return true;
                }
            });
            mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
        }
    }
    //获取验证码
    private void toChangeNewPhone(){
        RequestManager
        .mRetrofitManager
        .createRequest(RetrofitRequestInterface.class)
        .getOldValidCode()
        .enqueue(new RetrofitCallBack() {
            @Override
            public void onSuccess(String response) {
                Logger.i(TAG, response);
                JSONObject jsonObject = JSON.parseObject(response);
                String rCode = jsonObject.getString("code");
                String rMsg  = jsonObject.getString("msg");
                if("1000".equals(rCode)) {
                    sendValidCode = true;
                    tvPhoneChange.setVisibility(View.INVISIBLE);
                    tvGetValidCode.setVisibility(View.VISIBLE);
                    timer.start();
                    Toast.makeText(mContext,"验证码发送成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(mContext,rMsg,Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(Throwable t) {
                Logger.i(TAG, t.getMessage());
                Toast.makeText(mContext,"获取验证码失败"+t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }


    @SuppressLint("WrongConstant")
    private void showPopupValidCodeWindow() {
        if (mPopupValidCodeWindow != null && mPopupValidCodeWindow.isShowing()) {
            mPopupValidCodeWindow.dismiss();
        } else {
            View view = mInflater.inflate(R.layout.pop_phone_validcode, null);
            tvGetValidCode = view.findViewById(R.id.tv_pop_phone_getvalidcode);
            tvPhoneChange = view.findViewById(R.id.tv_phone_change);
            tvTime = view.findViewById(R.id.tv_time);
            VerificationCodeView et_rectangle = view.findViewById(R.id.et_rectangle);
            et_rectangle.getEditText().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                @Override
                public void afterTextChanged(Editable s) {
                    if(et_rectangle.getInputContent().length()==4){
                        String code = et_rectangle.getInputContent();
                        toCheckPhoneValidCode(code);
                    }
                }
            });
            tvGetValidCode.setEnabled(false);
            tvGetValidCode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(sendValidCode){
                        toChangeNewPhone();
                    }
                }
            });
            tvPhoneChange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toChangeNewPhone();
                }
            });
            mPopupValidCodeWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            mPopupValidCodeWindow.setSoftInputMode(INPUT_METHOD_NEEDED);
            mPopupValidCodeWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mPopupValidCodeWindow.setFocusable(true);
            mPopupValidCodeWindow.getContentView().setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mPopupValidCodeWindow.setFocusable(false);
                    mPopupValidCodeWindow.dismiss();
                    return true;
                }
            });
            mPopupValidCodeWindow.showAtLocation(view, Gravity.NO_GRAVITY, 0, 0);
            sendValidCode = false;
        }
    }

    public void toCheckPhoneValidCode(String code){
        if(checkValidCode(code)) {
            mPopupValidCodeWindow.dismiss();
            toNewPhoneActivity(code);
        }
    }

    public boolean checkValidCode(String code){
        if(code.length()!=4){
            Toast.makeText(mContext,"请输入验证码"+code.length(),Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void toNewPhoneActivity(String code){
        Intent intent = new Intent(this,ChangePhoneActivity.class);
        intent.putExtra("validCode",code);
        startActivity(intent);
    }

    private void updateApk(String downloadUrl, String forceUpdate) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            downLoadApk(downloadUrl, forceUpdate);

        } else {
            Toast.makeText(SettingActivity.this, "SD卡不可用，请插入SD卡", Toast.LENGTH_LONG).show();
        }
    }
    ProgressDialog progressDialog;

    private void downLoadApk(String downloadUrl, final String forceUpdate) {
        //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog = new ProgressDialog(SettingActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setProgress(0);
        progressDialog.show();

        OkHttpUtils.get().url(downloadUrl).build()
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "wlbx.apk") {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Logger.i(TAG, "onError :" + e.getMessage());

                    }

                    @Override
                    public void onResponse(final File file, int id) {
                        Logger.i(TAG, "onResponse :" + file.getAbsolutePath());
                        installApk(file.getAbsolutePath(), forceUpdate);
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        super.inProgress(progress, total, id);
                        Logger.i(TAG, (int) (100 * progress) + "%");
                        downLoading((int) (100 * progress));
                    }
                });
    }

    private void installApk(final String filePath, final String forceUpdate) {

        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        new AlertDialog.Builder(SettingActivity.this).setTitle("下载完成").setCancelable(false)
                .setMessage("是否安装")
                .setPositiveButton(
                        "是",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {



                                File file = new File(filePath);

//更新包文件
                                Intent intent = new Intent();

                                intent.setAction(Intent.ACTION_VIEW);

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)

                                { // Android7.0及以上版本 Log.d("-->最新apk下载完毕","Android N及以上版本");

                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                                    Uri contentUri = FileProvider.getUriForFile(SettingActivity.this, "com.wlbx.agent.fileprovider", file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

                                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

                                } else {

// Android7.0以下版本 Log.d("-->最新apk下载完毕","Android N以下版本");

                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                }

                                startActivity(intent);


                            }
                        }
                ).setNegativeButton(
                R.string.cancel, new DialogInterface.OnClickListener() {
                    //添加返回按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//响应事件

                    }

                }
        ).show();//在按键响应事件中显示此对话框


    }


    /**
     * 进度条实时更新
     *
     * @param i
     */
    public void downLoading(final int i) {
        SettingActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.setProgress(i);
            }
        });
    }
    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvTime.setText("("+millisUntilFinished/1000 + "s)");
        }

        @Override
        public void onFinish() {
            tvGetValidCode.setEnabled(true);
            tvTime.setText("");
        }
    };

}